import React, { useEffect, useRef, useState } from "react";

const CesiumViewer = () => {
  const viewerContainer = useRef(null);
  const handlerRef = useRef(null);
  const pointsRef = useRef([]); // 存储当前绘制的点
  const tempEntitiesRef = useRef([]); // 存储临时实体（点和线）
  const polygonsRef = useRef([]); // 存储绘制完成的多边形
  const [isDrawing, setIsDrawing] = useState(false); // 控制绘制状态

  useEffect(() => {
    if (!viewerContainer.current) {
      console.error("Viewer container is not available!");
      return;
    }

    try {
      if (!window.viewer) {
        // 避免重复创建 Viewer
        window.Cesium.Ion.defaultAccessToken =
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwOTcyNGVjYS1hMzIyLTQ1MzYtODY2MS04OTU1ODAxOTAwZWYiLCJpZCI6MjI1MTUxLCJpYXQiOjE3MzcxNzQyMjB9.gfYvMJAisENnLmeHf2smFLwq98Rl9_4IcgBELBgtZkc";

        window.viewer = new window.Cesium.Viewer(viewerContainer.current, {
          animation: false, // 禁用动画按钮
          timeline: false, // 禁用时间轴
          baseLayerPicker: false, // 禁用图层选择器
          navigationHelpButton: false, // 禁用帮助按钮
          sceneModePicker: false, // 禁用场景模式选择器（地球/2D等模式选择）
          geocoder: false, // 禁用搜索框
          homeButton: false, // 禁用回到初始位置按钮
          fullscreenButton: false, // 禁用全屏按钮
          vrButton: false, // 禁用VR按钮
        });

        // 强制隐藏 Cesium Ion 版权信息
        const creditContainer = window.viewer._cesiumWidget._creditContainer;
        creditContainer.style.display = "none";

        // 设置初始视角为中国地区
        window.viewer.camera.setView({
          destination: window.Cesium.Cartesian3.fromDegrees(105, 40, 15000000.0),
        });

        // 加载中国边界数据
        const chinaBoundary = window.Cesium.GeoJsonDataSource.load(
          "china_boundary.geojson"
        );
        chinaBoundary
          .then((dataSource) => {
            window.viewer.dataSources.add(dataSource);
            const entities = dataSource.entities.values;
            entities.forEach((entity) => {
              entity.polygon.outline = true;
              entity.polygon.outlineColor = window.Cesium.Color.RED;
              entity.polygon.outlineWidth = 3;
              entity.polygon.material = window.Cesium.Color.TRANSPARENT;
            });
          })
          .catch((error) => {
            console.error("Failed to load China boundary:", error);
          });
      }
    } catch (error) {
      console.error("Cesium is not loaded properly:", error);
    }
  }, []);

  // 启用绘制
  const enableDrawing = () => {
    setIsDrawing(true);
    if (!window.viewer) return;

    // 允许连续绘制，先清除上次的临时数据
    clearDrawing();

    const controller = window.viewer.scene.screenSpaceCameraController;
    controller.enableRotate = false;
    controller.enableTranslate = false;
    controller.enableTilt = false;
    controller.enableZoom = false;

    handlerRef.current = new window.Cesium.ScreenSpaceEventHandler(
      window.viewer.scene.canvas
    );
    setupDrawingEvents();
  };

  // **停止绘制**
  const stopDrawing = () => {
    setIsDrawing(false);
    if (handlerRef.current) {
      handlerRef.current.destroy(); // 彻底移除事件监听
      handlerRef.current = null;
    }
    cleanupDrawing();
  };

  // 设置绘制事件
  const setupDrawingEvents = () => {
    const handler = handlerRef.current;

    // 左键点击添加点
    handler.setInputAction((click) => {
      const position = getValidPosition(click.position);
      if (!position) return;

      pointsRef.current.push(position);
      addTempPoint(position);
      updatePreviewLine();
    }, window.Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 鼠标移动预览线
    handler.setInputAction((movement) => {
      if (pointsRef.current.length === 0) return;
      const currentPos = getValidPosition(movement.endPosition);
      if (!currentPos) return;

      updatePreviewLine(currentPos);
    }, window.Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // 右键完成绘制
    handler.setInputAction(() => {
      if (pointsRef.current.length < 3) {
        clearDrawing();
        return;
      }
      generatePolygon();
      clearDrawing();
    }, window.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  };

  // 获取有效坐标
  const getValidPosition = (screenPos) => {
    try {
      const ray = window.viewer.camera.getPickRay(screenPos);
      const cartesian = window.viewer.scene.globe.pick(ray, window.viewer.scene);
      return cartesian;
    } catch (error) {
      console.warn("坐标获取失败:", error);
      return null;
    }
  };

  // 添加临时点
  const addTempPoint = (position) => {
    const point = window.viewer.entities.add({
      position,
      point: {
        color: window.Cesium.Color.RED,
        pixelSize: 8,
        heightReference: window.Cesium.HeightReference.CLAMP_TO_GROUND,
      },
    });
    tempEntitiesRef.current.push(point);
  };

  // 更新预览线
  const updatePreviewLine = (currentPos) => {
    tempEntitiesRef.current
      .filter((e) => e.polyline)
      .forEach((e) => window.viewer.entities.remove(e));

    if (pointsRef.current.length === 0) return;

    const positions = [...pointsRef.current];
    if (currentPos) positions.push(currentPos);

    const line = window.viewer.entities.add({
      polyline: {
        positions,
        width: 2,
        material: window.Cesium.Color.YELLOW,
        clampToGround: true,
      },
    });
    tempEntitiesRef.current.push(line);
  };

  // 生成多边形
  const generatePolygon = () => {
    try {
      const coordinates = pointsRef.current.map(cartesian => {
        const carto = window.Cesium.Cartographic.fromCartesian(cartesian);
        return [
          window.Cesium.Math.toDegrees(carto.longitude),
          window.Cesium.Math.toDegrees(carto.latitude)
        ];
      });
      coordinates.push(coordinates[0]); // 闭合多边形

      console.log("绘制完成，Polygon 坐标:", coordinates);

      const polygon = window.viewer.entities.add({
        polygon: {
          hierarchy: new window.Cesium.PolygonHierarchy(
            coordinates.map(coord => window.Cesium.Cartesian3.fromDegrees(coord[0], coord[1]))
          ),
          material: window.Cesium.Color.RED.withAlpha(0.5),
          outline: true,
          outlineColor: window.Cesium.Color.BLACK,
          outlineWidth: 2,
        }
      });

      polygonsRef.current.push(polygon);
    } catch (error) {
      console.error("坐标转换失败:", error);
    }
  };

  // 清理临时绘图资源（但保留已绘制的多边形）
  const cleanupDrawing = () => {
    const controller = window.viewer.scene.screenSpaceCameraController;
    controller.enableRotate = true;
    controller.enableTranslate = true;
    controller.enableTilt = true;
    controller.enableZoom = true;
  
    // 清除临时点和线
    tempEntitiesRef.current.forEach((e) => window.viewer.entities.remove(e));
    tempEntitiesRef.current = [];
  
    // 清除已绘制的多边形
    polygonsRef.current.forEach((polygon) => window.viewer.entities.remove(polygon));
    polygonsRef.current = [];
  
    // 清空点数据
    pointsRef.current = [];
  
    // 解绑事件监听，确保彻底退出绘制状态
    if (handlerRef.current) {
      handlerRef.current.destroy();
      handlerRef.current = null;
    }
  };

  // 清除当前绘制（但不删除已经绘制的多边形）
  const clearDrawing = () => {
    tempEntitiesRef.current.forEach((e) => window.viewer.entities.remove(e));
    tempEntitiesRef.current = [];
    pointsRef.current = [];
  };
  return (
    <div style={{ height: "100%", width: "100%" }} ref={viewerContainer}>
      {/* 开始/停止绘制按钮 */}
      <div style={{ position: "absolute", top: "50px", left: "10px", zIndex: 1000 }}>
        {!isDrawing ? (
          <button
            style={{
              padding: "8px 16px",
              backgroundColor: "#2196F3",
              color: "white",
              border: "none",
              borderRadius: "4px",
              cursor: "pointer",
            }}
            onClick={enableDrawing}
          >
            开始绘制
          </button>
        ) : (
          <button
            style={{
              padding: "8px 16px",
              backgroundColor: "#f44336",
              color: "white",
              border: "none",
              borderRadius: "4px",
              cursor: "pointer",
            }}
            onClick={stopDrawing}
          >
            停止绘制
          </button>
        )}
      </div>
    </div>
  );
};

export default CesiumViewer;